<template>
  <div class="banner">
    Personal Center
  </div>
  <br>
  <el-row>
    <el-col :span="4"></el-col>
    <el-col :span="16">
      <el-card>
        <h3 style="font-weight: bolder;color: #036b67">个人信息</h3>
        <div style="display: flex;align-items: center;text-align: center">
          <!-- 头像 -->
          <div style="flex:0.4">
            <el-image :src="store.getHeaderImg"
                      style="width: 60%;border-radius: 20%;border: 1px solid #eeeeee"></el-image>
          </div>
          <!-- 分割线 -->
          <el-divider direction="vertical" style="height: 200px"></el-divider>
          <!--  个人信息-->
          <div style="flex:1;padding: 40px;text-align: left">
            <table class="infoTable">
              <tbody>
              <tr>
                <td style="width: 25%">昵称：</td>
                <td>{{ store.userInfo.userNickName }}</td>
              </tr>
              <tr>
                <td>签名：</td>
                <td>{{ store.userInfo.signature }}</td>
              </tr>
              <tr>
                <td>邮箱：</td>
                <td>{{ store.userInfo.email }}</td>
              </tr>
              <tr>
                <td>注册时间：</td>
                <td>{{ store.userInfo.registerTime }}</td>
              </tr>
              <tr>
                <td>最后登录时间：</td>
                <td>{{ store.userInfo.lastLoginTime }}</td>
              </tr>
              </tbody>
            </table>
            <br>
            <el-button @click="editUserInfo">修改信息</el-button>

          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="4"></el-col>
  </el-row>

  <!--添加标签弹出框-->
  <el-dialog
      v-model="dialogVisible"
      title="修改个人信息"
      width="30%"
      :before-close="handleClose">
    <el-form ref="formRef"
             :model="userInfoForm"
             :rules="rules"
             label-width="80px">
      <el-form-item label="用户名" prop="userUsername">
        <el-input v-model="userInfoForm.userUsername" type="text" maxlength="12"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="昵称" prop="userNickName">
        <el-input v-model="userInfoForm.userNickName" type="text" maxlength="12"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfoForm.email" type="text" maxlength="20"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="签名" prop="signature">
        <el-input v-model="userInfoForm.signature" type="text" maxlength="255"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="密码" prop="userPassword">
        <el-input v-model="userInfoForm.userPassword" type="password" minlength="6"
                  show-word-limit placeholder="不填写表示不修改密码"/>
      </el-form-item>

      <!--  分类的图标  -->
      <el-form-item label="头像" prop="headerImg">
        <el-upload
            class="avatar-uploader"
            name="headerImg"
            :auto-upload="true"
            action="/api/user/uploadHeadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="getUploadImgUrl" :src="getUploadImgUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="save">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>


</template>

<script>
import userStore from "@/store/UserStore";
import pinia from "@/store/pinia";
import {ElMessage} from "element-plus";

const store = userStore(pinia);

export default {
  name: "UserCenter",
  computed: {
    getUploadImgUrl() {
      if (this.uploadImgUrl) {
        return this.uploadImgUrl
      } else {
        return ""
      }
    },
  },
  data() {
    return {
      store,
      uploadImgUrl: '',
      dialogVisible: false,
      userInfoForm: {
        userId: 0,
        userNickName: "",
        userUsername: "",
        userPassword: null,
        signature: "",
        email: "",
        headImg: "",
        registerTime: '',
        lastLoginTime: '',
      },
      rules: {
        userNickName: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
          {min: 2, max: 12, message: '用户昵称长度应该在2-12位', trigger: 'blur'},
        ],
        userUsername: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 5, max: 12, message: '用户名长度应该在5-12位', trigger: 'blur'},
        ],
        userPassword: [
          {min: 6, max: 24, message: '密码长度应该在6-24位', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    handleClose() {
      this.$refs.formRef.resetFields()
      // 设置为初始状态
      this.$data.userInfoForm = this.$options.data().userInfoForm
      this.uploadImgUrl = ""
      this.dialogVisible = false
    },
    // 打开修改对话框
    editUserInfo() {
      this.dialogVisible = true
      this.uploadImgUrl = this.store.userInfo.headImg
      this.userInfoForm.userUsername = this.store.userInfo.userUsername
      this.userInfoForm.userNickName = this.store.userInfo.userNickName
      this.userInfoForm.email = this.store.userInfo.email
      this.userInfoForm.headImg = this.store.userInfo.headImg
      this.userInfoForm.signature = this.store.userInfo.signature
    },
    async updataUserInfo(){
      let {data: result} = await this.$http.get("/api/user/getUserInfo")
      this.store.updateUserInfo(result)
    },
    // 保存到数据库
    async save() {
      // 检查用户名可用性
      let usernameCanUse = this.checkUsernameCanUse();
      if (!usernameCanUse) {
        ElMessage.error({showClose: true, message: "用户名不可用！"})
        return false
      }
      // 修改个人信息
      await this.$refs.formRef.validate(async (isValid) => {
        if (isValid) {
          let {data: result} = await this.$http.post("/api/user/editSelfInfo", this.userInfoForm)
          if (result.code === 200) {
            ElMessage.success({showClose: true, message: result.msg})
            this.handleClose()
            // 修改store中的userinfo
            this.updataUserInfo()
          } else {
            ElMessage.error({showClose: true, message: result.msg})
          }
        } else {
          ElMessage.error("表单填写有误！")
        }
      })
    },
    async checkUsernameCanUse() {
      let {data: result} = await this.$http.get("/api/user/checkUsernameCanUse", {
        params: {
          username: this.userInfoForm.userUsername,
          userId: this.store.userInfo.userId
        }
      })
      return result
    },

    // 上传前检查文件格式和大小
    beforeAvatarUpload(rawFile) {
      let allowTypes = ['image/jpeg', "image/jpg", 'image/png', 'image/webp', 'image/icon'];
      if (!allowTypes.includes(rawFile.type)) {
        ElMessage.error('文件格式不正确!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能大于 2MB!')
        return false
      }
      return true
    },
    // 上传成功修改预览
    handleAvatarSuccess(response) {
      console.log(response)
      let {code, dataMap} = response
      this.uploadImgUrl = dataMap.imgPath
      this.userInfoForm.headImg = dataMap.imgPath
    },
  }
}
</script>

<style scoped>
.banner {
  background-image: url('/headImg/userCenter.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 400px;
  width: 100%;

  color: white;
  font-size: 3em;
  font-weight: bolder;
  text-align: center;
  padding-top: 200px;
}

p, h3, h4 {
  line-height: 2;
}

.infoTable {
  width: 100%;
}

.infoTable td {
  height: 3em;
  border: none;
  border-bottom: 1px solid #eeeeee;
}

/*头像上传框的css*/
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  /*margin-left: 30px;*/
  border-radius: 20px;
}

.avatar-uploader {
  border: 1px solid #8c939d;
  border-radius: 20px;
  margin-left: 30px;
  height: 150px;
  width: 150px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 60px;
  align-items: center;
  text-align: center;
}
</style>